import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';

/// 本地存储工具类
class StorageUtils {
  static SharedPreferences? _prefs;

  /// 初始化
  static Future<void> init() async {
    _prefs ??= await SharedPreferences.getInstance();
  }

  /// 存储字符串
  static Future<bool> setString(String key, String value) async {
    await init();
    return await _prefs!.setString(key, value);
  }

  /// 获取字符串
  static String? getString(String key) {
    return _prefs?.getString(key);
  }

  /// 存储整型
  static Future<bool> setInt(String key, int value) async {
    await init();
    return await _prefs!.setInt(key, value);
  }

  /// 获取整型
  static int? getInt(String key) {
    return _prefs?.getInt(key);
  }

  /// 存储布尔值
  static Future<bool> setBool(String key, bool value) async {
    await init();
    return await _prefs!.setBool(key, value);
  }

  /// 获取布尔值
  static bool? getBool(String key) {
    return _prefs?.getBool(key);
  }

  /// 存储对象
  static Future<bool> setObject(String key, Object value) async {
    await init();
    return await _prefs!.setString(key, jsonEncode(value));
  }

  /// 获取对象
  static dynamic getObject(String key) {
    final value = _prefs?.getString(key);
    if (value == null) return null;
    try {
      return jsonDecode(value);
    } catch (e) {
      return null;
    }
  }

  /// 是否存在key
  static bool containsKey(String key) {
    return _prefs?.containsKey(key) ?? false;
  }

  /// 移除key
  static Future<bool> remove(String key) async {
    await init();
    return await _prefs!.remove(key);
  }

  /// 清除所有
  static Future<bool> clear() async {
    await init();
    return await _prefs!.clear();
  }
}
